#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "err.hpp"
#include "udp_client.hpp"

static void usage(std::string proc) {
    std::cout << "Usage:\n\t" << proc << "serverip serverport\n" << std::endl;
}

void *recver(void *args) {
    int sock = *(static_cast<int*>(args));
    while (true) {
        char buffer[1024];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        int n = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&temp, &len);
        if (n > 0) {
            buffer[n] = '\0';
            std::cout << buffer << std::endl;
        }
    }
}

// ./udp_client server_ip server_port
int main(int argc, char* argv[]) {
    if (argc != 3) {
        usage(argv[0]);
        exit(USAGE_ERR);
    }

    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) {
        std::cerr << "create socket error: " << strerror(errno) << std::endl;
        exit(SOCKET_ERR);
    }

    // 客户端也要bind，但不需要自己bind，OS自动给我们bind -- 大量软件的端口号要由操作系统去分配
    // 在我们首次系统调用发送数据的时候，OS会在底层随机选择clientport+自己的IP 1.bind 2.构建数据报文
    // 服务端的端口号不能随意改变

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(serverport);

    pthread_t tid;
    pthread_create(&tid, nullptr, recver, &sock);

    while (true) {
        std::string message;
        std::cerr << "please Enter# ";
        // std::cin >> message;
        std::getline(std::cin, message);

        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));

        
    }
    return 0;
}